package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FirePictureVideoAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.FireTaskBean;
import com.mingtu.guards.utils.MyConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class FireTaskActivity extends MyBaseActivity {

    @BindView(R.id.tv_task_title)
    TextView tvTaskTitle;
    @BindView(R.id.tv_task_type)
    TextView tvTaskType;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_fire_status)
    TextView tvFireStatus;
    @BindView(R.id.tv_warning_type)
    TextView tvWarningType;
    @BindView(R.id.tv_warning_time)
    TextView tvWarningTime;
    @BindView(R.id.tv_fire_location)
    TextView tvFireLocation;
    @BindView(R.id.iv_fire_location)
    ImageView ivFireLocation;
    @BindView(R.id.tv_fire_lng_lat)
    TextView tvFireLngLat;
    @BindView(R.id.tv_map_grid)
    TextView tvMapGrid;
    @BindView(R.id.tv_dept_name)
    TextView tvDeptName;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_person_phone)
    TextView tvPersonPhone;
    @BindView(R.id.recycler_picture_video)
    RecyclerView recyclerPictureVideo;
    @BindView(R.id.but_submit)
    Button butSubmit;
    private String taskId;
    private String taskType;
    private List<FireTaskBean.DataBean.FireInfoEntityBean.FireInfoAttachEntityListBean> DataBean = new ArrayList<>();
    private ArrayList<LocalMedia> selectPictureList;
    private String createTime;
    private FirePictureVideoAdapter firePictureVideoAdapter;
    private String lngStr;
    private String latStr;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fire_task;
    }

    @Override
    protected void initView() {
        setModuleTitle("任务详情");
    }

    @Override
    protected void initData() {
        taskId = getIntent().getStringExtra("taskId");
        taskType = getIntent().getStringExtra("taskType");
        if (!StringUtils.isEmpty(taskId)) {
            getTaskDetails();
        } else {
            ToastUtils.showLong(getResources().getString(R.string.data_error));
        }

        GridLayoutManager layoutManager1 = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        recyclerPictureVideo.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(ItemDecorationSpaces), false));
        recyclerPictureVideo.setLayoutManager(layoutManager1);

        firePictureVideoAdapter = new FirePictureVideoAdapter(context, DataBean);
        recyclerPictureVideo.setAdapter(firePictureVideoAdapter);
        firePictureVideoAdapter.setOnItemClickListener(new FirePictureVideoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList);
            }
        });
    }

    @Override
    protected void getData() {
        getTaskDetails();
    }

    @OnClick({R.id.iv_fire_location, R.id.but_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_fire_location:
                Bundle bundle1 = new Bundle();
                bundle1.putString("lng", lngStr);
                bundle1.putString("lat", latStr);
                IntentUtils.getInstance().readyGo(FireTaskActivity.this, NaviMapActivity.class, bundle1);
                break;
            case R.id.but_submit:
                Bundle bundle2 = new Bundle();
                bundle2.putString("taskId", taskId);
                IntentUtils.getInstance().readyGo(FireTaskActivity.this, FireTaskSureActivity.class, bundle2);
                break;
        }
    }

    /**
     * 火情任务待确认详情
     */
    private void getTaskDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", taskId);
        hashMap.put("type", taskType);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SUPER_DETAILS)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            FireTaskBean fireTaskBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                fireTaskBean = new FireTaskBean();
                                fireTaskBean = gson.fromJson(result, FireTaskBean.class);

                                FireTaskBean.DataBean infoBean = fireTaskBean.getData();
                                recyclerPictureVideo.setVisibility(View.GONE);
                                if (infoBean != null) {
                                    String name = infoBean.getName();
                                    createTime = infoBean.getCreateTime();
                                    String finishTime = infoBean.getFinishTime();
                                    FireTaskBean.DataBean.FireInfoEntityBean fireInfoEntityBean = infoBean.getFireInfoEntity();

                                    if (!StringUtils.isEmpty(name)) {
                                        tvTaskTitle.setText(name);
                                    }

                                    if (!StringUtils.isEmpty(createTime)) {
                                        tvStartTime.setText(createTime);
                                    }

                                    if (!StringUtils.isEmpty(finishTime)) {
                                        tvEndTime.setText(finishTime);
                                    }

                                    if (fireInfoEntityBean != null) {
                                        String uploadType = fireInfoEntityBean.getUploadType();
                                        String warningTime = fireInfoEntityBean.getCreateTime();
                                        String fireAddress = fireInfoEntityBean.getAddress();
                                        String lnglat = fireInfoEntityBean.getLnglat();
                                        String gridId = fireInfoEntityBean.getGridId();
                                        String deptName = fireInfoEntityBean.getDeptName();
                                        String manager = fireInfoEntityBean.getManager();
                                        String mobile = fireInfoEntityBean.getMobile();

                                        List<FireTaskBean.DataBean.FireInfoEntityBean.FireInfoAttachEntityListBean>
                                                listBeans = fireInfoEntityBean.getFireInfoAttachEntityList();


                                        if (lnglat.indexOf(",") != -1) {
                                            String[] lnglatArray = lnglat.split(",");
                                            lngStr = lnglatArray[0];
                                            latStr = lnglatArray[1];
                                            double lat = Double.parseDouble(latStr);
                                            double lng = Double.parseDouble(lngStr);
                                            String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                                            String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);
                                            tvFireLngLat.setText(myLng + "," + myLat);
                                        }
                                        if (!StringUtils.isEmpty(uploadType)) {
                                            tvWarningType.setText(uploadType);
                                        }
                                        if (!StringUtils.isEmpty(warningTime)) {
                                            tvWarningTime.setText(warningTime);
                                        }
                                        if (!StringUtils.isEmpty(fireAddress)) {
                                            tvFireLocation.setText(fireAddress);
                                        }

                                        if (!StringUtils.isEmpty(gridId)) {
                                            tvMapGrid.setText(gridId);
                                        }
                                        if (!StringUtils.isEmpty(deptName)) {
                                            tvDeptName.setText(deptName);
                                        }
                                        if (!StringUtils.isEmpty(manager)) {
                                            tvPerson.setText(manager);
                                        }
                                        if (!StringUtils.isEmpty(mobile)) {
                                            tvPersonPhone.setText(mobile);
                                        }

                                        if (listBeans != null) {
                                            if (listBeans.size() > 0) {
                                                DataBean = new ArrayList<>();
                                                for (int i = 0; i < listBeans.size(); i++) { //将现场照片取出来
                                                    String type = listBeans.get(i).getType();  //1:现场照片   2：确认照片
                                                    if (type.equals("1")) {
                                                        DataBean.add(listBeans.get(i));
                                                    }
                                                }

                                                if (DataBean.size() > 0) {
                                                    recyclerPictureVideo.setVisibility(View.VISIBLE);
                                                    selectPictureList = new ArrayList<>();

                                                    for (int i = 0; i < DataBean.size(); i++) {
                                                        String url = DataBean.get(i).getUrl();
                                                        String resType = "1";  //1:图片   3：视频
                                                        boolean isHasVideo = PictureMimeType.isUrlHasVideo(url); //现在只有图片和视频，如果添加音频文件的话，此处逻辑要改
                                                        if (isHasVideo) {
                                                            resType = "3";
                                                        }
                                                        //设置资源类型，在adapter 中使用
                                                        DataBean.get(i).setResType(resType);

                                                        LocalMedia localMedia =  LocalMedia.generateHttpAsLocalMedia(url);
                                                        selectPictureList.add(localMedia);
                                                    }
                                                    firePictureVideoAdapter.upData(DataBean);
                                                }
                                            }
                                        }
                                    }

                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }
}